<template>
  <div class="rechargeRulesEdit-container">
    <LaiHeader
      @go-back="router.back()"
      @on-confirm="handleSubmit"
      is-show-back
      :title="dialogProps.title + '充值规则'"
      :is-show-button="!dialogProps.isView"
      button-text="确定"
      :height="70"
    ></LaiHeader>

    <div class="form-box">
      <el-form
        ref="ruleFormRef"
        label-width="140px"
        label-suffix=" :"
        :rules="rules"
        :disabled="dialogProps.isView"
        :model="dialogProps.row"
        :hide-required-asterisk="dialogProps.isView"
      >
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="基本信息" :name="1">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="充值活动名称" prop="name">
                  <el-input v-model="dialogProps.row!.name" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="充值类型" prop="depositType">
                  <el-radio-group v-model="dialogProps.row!.depositType">
                    <el-radio :label="1">充值金额</el-radio>
                    <!-- <el-radio :label="2">充次数</el-radio> -->
                  </el-radio-group>
                </el-form-item>
                <template v-if="dialogProps.row.depositType === 1">
                  <el-form-item label="充值金额" prop="depositMoney">
                    <el-input-number class="w100" :min="0" v-model="dialogProps.row!.depositMoney" :controls="false" />
                  </el-form-item>
                  <el-form-item label="赠送金额" prop="giveMoney">
                    <el-input-number class="w100" v-model="dialogProps.row!.giveMoney" :controls="false" />
                  </el-form-item>
                </template>
                <!-- <template v-if="dialogProps.row.depositType === 2">
                  <el-form-item
                    label="充值次数"
                    prop="parValue"
                    :rules="dialogProps.row.depositType === 2 ? [{ required: true, message: '请输入' }] : [{ required: false }]"
                  >
                    <el-input-number class="w100" v-model="dialogProps.row!.parValue" :controls="false" />
                  </el-form-item>
                  <el-form-item label="赠送次数" prop="parValue">
                    <el-input-number class="w100" v-model="dialogProps.row!.giftValue" :controls="false" />
                  </el-form-item>
                </template> -->
                <el-form-item label="赠送积分" prop="giveIntegral">
                  <el-input-number class="w100" v-model="dialogProps.row!.giveIntegral" :controls="false" />
                </el-form-item>
                <el-form-item label="上级赠送积分" prop="upGiveIntegral">
                  <el-input-number class="w100" v-model="dialogProps.row!.upGiveIntegral" :controls="false" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="dialogProps.row!.remark" placeholder="请填写"> </el-input>
                </el-form-item>

                <!-- <el-form-item label="限制参与会员分类" prop="userCategoryId">
                  <el-select class="w100" v-model="dialogProps.row!.userCategoryId" placeholder="请选择" clearable>
                    <el-option v-for="item in optionsCategory" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item> -->

                <el-form-item label="可参与会员等级" prop="row.userGradeObject">
                  <el-checkbox-group v-model="dialogProps.row!.userGradeObject">
                    <el-checkbox :label="item.title" :value="item.id" v-for="item in memberList" :key="item.id" />
                  </el-checkbox-group>
                </el-form-item>

                <el-form-item label="状态" prop="depositRuleStatus">
                  <el-radio-group v-model="dialogProps.row!.depositRuleStatus">
                    <el-radio :label="1">正常</el-radio>
                    <el-radio :label="2">停用</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="是否累加" prop="isAccumulation">
                  <el-radio-group v-model="dialogProps.row!.isAccumulation">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="2">否</el-radio>
                  </el-radio-group>
                </el-form-item>
                <!--  <el-form-item label="赠送礼券" prop="couponId">
              <div v-if="false" style="display: flex; align-items: center; color: #efb43f" @click="addCoupon()">
                添加优惠券<el-icon style="margin-left: 5px" size="18" color="#efb43f"><CirclePlus /></el-icon>
              </div>

              <div class="tag-box" v-else>
                <div class="tag-content">
                  <el-tag type="primary" style="margin-right: 5px" closable v-for="item in 19" :key="item">Tag 1</el-tag>
                </div>
                <el-icon @click="addCoupon(true, couponList)" color="#efb43f" size="25" style="margin-left: 5px">
                  <CirclePlus />
                </el-icon>
              </div>

               <el-select class="w100" v-model="dialogProps.row!.couponId" placeholder="请选择" clearable>
                <el-option v-11for="item in optionsCoupon" :key="item.id" :label="item.name" :value="item.id" />
              </el-select> -->

                <!-- <el-input v-model="dialogProps.row!.couponId" disabled>
                <template #prepend>
                  <el-button type="primary" :icon="MoreFilled" @click="addGift"></el-button>
                </template>
              </el-input>
            </el-form-item> -->

                <el-form-item label="绑定会员等级" prop="grade">
                  <el-select class="w100" v-model="dialogProps.row!.grade" placeholder="请选择" clearable>
                    <el-option v-for="item in memberList.slice(1)" :key="item.id" :value="item.id" :label="item.title" />
                  </el-select>
                  <div style="color: #999999">用户充值该活动自动升级为该等级会员</div>
                </el-form-item>
                <!-- <el-form-item> </el-form-item> -->

                <el-form-item label="开始时间" prop="startTime">
                  <el-date-picker
                    style="width: 100%"
                    v-model="dialogProps.row!.startTime"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                  <el-date-picker
                    style="width: 100%"
                    v-model="dialogProps.row!.endTime"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>

                <!-- <el-form-item label="礼券数量" prop="couponCount">
              <el-input-number class="w100" v-model="dialogProps.row!.couponCount" :controls="false" />
            </el-form-item> -->

                <el-form-item label="赠送礼券" prop="couponId">
                  <div
                    v-if="couponList.length < 1"
                    style="display: flex; align-items: center; color: #efb43f"
                    @click="addCoupon(false)"
                  >
                    添加优惠券<el-icon style="margin-left: 5px" size="18" color="#efb43f"><CirclePlus /></el-icon>
                  </div>

                  <div class="tag-box" v-else>
                    <div class="table">
                      <el-table :data="couponList" border style="width: 100%">
                        <el-table-column prop="name" width="120" label="礼券名字"></el-table-column>
                        <el-table-column prop="count" width="120" label="券数量">
                          <template #default="{ row, $index }">
                            <el-input-number
                              @change="changeCount($index, row)"
                              :controls="false"
                              class="w80"
                              :min="1"
                              v-model="row.count"
                            ></el-input-number>
                          </template>
                        </el-table-column>
                        <el-table-column prop="typeName" width="100" label="券类型"></el-table-column>
                        <el-table-column prop="validityDesc" label="有效期"></el-table-column>
                        <!-- <el-table-column prop="startDate" width="180" label="开始时间"></el-table-column>
                    <el-table-column prop="endDate" width="180" label="结束时间"></el-table-column> -->
                        <el-table-column label="操作" width="100" fixed="right">
                          <template #default="{ $index }">
                            <el-button type="text" @click="onDel($index)">删除</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                    <el-icon @click="addCoupon(true)" color="#efb43f" size="25" style="margin-left: 5px">
                      <CirclePlus />
                    </el-icon>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- <el-tab-pane label="其他信息" :name="2">
            <el-row :gutter="10">
              <el-col :span="15">
               
              </el-col>
            </el-row>
          </el-tab-pane> -->

          <el-tab-pane label="其他信息" :name="2">
            <el-row :gutter="10">
              <el-col :span="15">
                <el-form-item label="广告图" prop="image">
                  <IMG v-model:image-url="dialogProps.row.image" />
                </el-form-item>
                <el-form-item>
                  <div style="color: #999999">建议上传图片：3 : 2 （例：宽375px 高250px）</div>
                </el-form-item>
                <el-form-item label="活动说明">
                  <WangEditor
                    :disabled="dialogProps.isView"
                    v-model:value="dialogProps.row!.introduce"
                    height="330px"
                  ></WangEditor>
                  <div style="color: #999999">活动说明：上传图片后建议点击图片 100% 进行适配</div>
                </el-form-item>
                <el-form-item>
                  <div class="ml20 mt10">
                    <div>
                      <el-text type="info" size="small">
                        提示1:充值金额和赠送金额都为0时,前台可输入赠送金额；赠送次数为-1,前台可输入赠送次数
                      </el-text>
                    </div>
                    <div class="mt5">
                      <el-text type="info" size="small">
                        提示2:充值金额和赠送金额都为0时,赠送积分为每元赠送多少积分，次卡的积分赠送在次卡方案设置
                      </el-text>
                    </div>
                    <div class="mt5">
                      <el-text type="info" size="small">提示3:不选择会员分类时,所有会员都适用该规则</el-text>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>
    <CouponDialog @on-confirm="onConfirm" @on-reset="onReset" @on-search="searchCoupon" ref="couponRef"></CouponDialog>
  </div>
</template>

<script setup lang="ts" name="rechargeRulesEdit">
import { ElMessage, FormInstance } from "element-plus";
import { onMounted, reactive, ref } from "vue";
// import { MoreFilled } from "@element-plus/icons-vue";
import { getFoodCouponList } from "@/api/modules/coupon";
import {
  createUserDepositRules,
  editUserDepositRules,
  getMemberGradeList,
  getUserDepositRulesDetails
} from "@/api/modules/member";
import IMG from "@/components/Upload/Img.vue";
import WangEditor from "@/components/WangEditor/index.vue";
import LaiHeader from "@/components/lai-header/index.vue";
import CouponDialog from "@/views/marketing/createActivity/components/CouponDialog.vue";
import { useRoute, useRouter } from "vue-router";

const router = useRouter();

const rules = reactive({
  name: [{ required: true, message: "会员名称必填" }],
  depositMoney: [{ required: true, message: "请输入充值金额" }],
  couponCount: [
    {
      validator: (rules: any, value: any, callBack: any) => {
        if (dialogProps.value.row.couponId && !value) {
          return callBack(new Error("请输入礼券数量"));
        }
        callBack();
      }
    }
  ],
  "row.userGradeObject": [
    {
      validator: (rules: any, value: any[], callBack: any) => {
        if (dialogProps.value.row.userGradeObject.length < 1) {
          return callBack(new Error("至少选择一项"));
        }
        callBack();
      }
    }
  ]
  // image: [{ required: true, message: "请上传图片" }]
});

interface DialogProps {
  title: string;
  isView: boolean;
  row: any;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

// const optionsCategory = ref<any[]>([]);
const optionsCoupon = ref<any[]>([]);
const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {
    couponsObject: []
    // depositMoney: 1,
    // couponCount: 1
  }
});

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      dialogProps.value.title === "新增"
        ? await createUserDepositRules(dialogProps.value.row)
        : dialogProps.value.title === "编辑"
        ? await editUserDepositRules(dialogProps.value.row)
        : ""; // 发请求后更新接口
      ElMessage.success({ message: `${dialogProps.value.title}规则成功！` });
      router.push("/member/rechargeRules?isUpdate=" + true);
    } catch (error) {
      console.log(error);
    }
  });
};
const route = useRoute();
const memberList = ref<any[]>([]);

onMounted(async () => {
  const params = JSON.parse(route.query.params as string);

  if (params.title === "编辑" || params.isView) {
    const res: any = await getUserDepositRulesDetails(params.row);
    dialogProps.value = params;
    dialogProps.value.row = res.data;
    couponList.value = res.data!.couponList;
    dialogProps.value.row.couponsObject = couponList.value.map(v => ({ id: v.id, count: v.count }));
  } else {
    dialogProps.value = JSON.parse(decodeURIComponent(route.query.params as string));
    dialogProps.value.row!.userGradeObject = [0];
  }
  Promise.all([
    // getUserCategoryList({ pageSize: 9999, pageNum: 1 }).then(res => {
    //   optionsCategory.value = res.data.list;
    // }),
    getMemberGradeList({ pageSize: 9999, pageNum: 1 }).then(res => {
      memberList.value = res.data.list;
      memberList.value.unshift({ title: "非会员", id: 0 });
    })
  ]);

  // getFoodCouponList({ pageSize: 9999, pageNum: 1 }).then(res => {
  //   optionsCoupon.value = res.data.list;
  // });
});

// 表格显示，选中数据，回填数据，删除数据

// 打开礼券
const couponList = ref<any[]>([]);
const couponRef = ref<InstanceType<typeof CouponDialog> | null>(null);
const addCoupon = async (isSelect?: boolean, parameter?: any) => {
  const res = await getFoodCouponList({ pageNum: 1, pageSize: 99999, isAvailable: true, ...parameter });

  if (isSelect) {
    res.data.list.forEach((v, i) => {
      couponList.value.forEach(e => {
        if (e.id === v.id) {
          v.isSelected = true;
        }
      });
    });
  }
  couponRef.value?.acceptParams({
    tableData: res.data.list,
    title: "优惠券列表",
    columns: [
      { type: "selection" },
      { prop: "name", label: "活动名称", width: 180 },
      { prop: "typeName", label: "券类型", width: 100 },
      { prop: "validityDesc", label: "有效期" }
      // { prop: "startDate", label: "开始时间" },
      // { prop: "endDate", label: "结束时间" }
    ],
    search: {
      label: "券名称：",
      type: "input",
      searchLabel: "券类型",
      mate: [
        { label: "代金券", value: 1 },
        { label: "商品兑换券", value: 2 },
        { label: "折扣券", value: 3 }
      ]
    }
  });
};
// 选中
const onConfirm = (e: any) => {
  couponList.value = e.tableData;
  dialogProps.value.row.couponsObject = couponList.value.map(v => ({ id: v.id, count: v.count }));
};
const changeCount = (index: number, row: any) => {
  dialogProps.value.row.couponsObject[index].count = row.count;
};
// 删除
const onDel = (index: number) => {
  couponList.value.splice(index, 1);
  dialogProps.value.row.couponsObject.splice(index, 1);
};

// 搜索优惠券
const searchCoupon = (e: any) => {
  addCoupon(true, { name: e.searchText, typeId: e.searchType || null });
};
const onReset = (e: any) => {
  addCoupon(true, {});
};

const activeName = ref(1);
</script>

<style lang="scss" scoped>
div {
  box-sizing: border-box;
}
.rechargeRulesEdit-container {
  height: 100%;
  overflow: hidden;
  .form-box {
    height: calc(100% - 70px);
    padding: 20px;
    margin-top: 10px;
    overflow-y: auto;
    background-color: #ffffff;
  }
  .tag-box {
    display: flex;
    align-items: center;
    width: 100%;
    .table {
      flex: 1;
      overflow: auto;
    }
  }
}
</style>
